package gui.passwordView;

import gui.mainView.UIView;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import commons.Manager;
import commons.User;
import commons.exceptions.PasswordException;


public class UIPasswdControler implements ActionListener {

	UIView parent;
	UIPasswordView uiPasswdView;

	public UIPasswdControler(UIPasswordView uiPasswdView, UIView parent){
		this.parent = parent;
		this.uiPasswdView = uiPasswdView;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(uiPasswdView.submit)){
			uiPasswdView.exceptionAdmin.setText("");
			uiPasswdView.exceptionGuest.setText("");
			String currentPasswd;
			String newPasswd;
			if(uiPasswdView.currentAdminPasswd.getPassword().length!=0 || uiPasswdView.newAdminPasswd.getPassword().length!=0){
				currentPasswd="";
				newPasswd="";
				try {
					for(int i=0;i<uiPasswdView.currentAdminPasswd.getPassword().length;i++){
						currentPasswd=currentPasswd+uiPasswdView.currentAdminPasswd.getPassword()[i];
					}
					for(int i=0;i<uiPasswdView.newAdminPasswd.getPassword().length;i++){
						newPasswd=newPasswd+uiPasswdView.newAdminPasswd.getPassword()[i];
					}
					Manager.getInstance().changeAdminPassword(currentPasswd,newPasswd);
					uiPasswdView.exceptionAdmin.setText("Password has been updated.");
					uiPasswdView.exceptionAdmin.setForeground(new Color(0,102,0));
					uiPasswdView.update();
				} catch (PasswordException e1) {
					uiPasswdView.exceptionAdmin.setText(e1.getMessage());
					uiPasswdView.exceptionAdmin.setForeground(Color.red);
					uiPasswdView.update();
				}
			}
			if(uiPasswdView.currentGuestPasswd.getPassword().length!=0 || uiPasswdView.newGuestPasswd.getPassword().length!=0){
				currentPasswd="";
				newPasswd="";
				try {
					for(int i=0;i<uiPasswdView.currentGuestPasswd.getPassword().length;i++){
						currentPasswd=currentPasswd+uiPasswdView.currentGuestPasswd.getPassword()[i];
					}
					for(int i=0;i<uiPasswdView.newGuestPasswd.getPassword().length;i++){
						newPasswd=newPasswd+uiPasswdView.newGuestPasswd.getPassword()[i];
					}
					Manager.getInstance().changeGuestPassword(currentPasswd,newPasswd);
					uiPasswdView.exceptionGuest.setText("Password has been updated.");
					uiPasswdView.exceptionGuest.setForeground(new Color(0,102,0));
					uiPasswdView.update();
				} catch (PasswordException e1) {
					uiPasswdView.exceptionGuest.setText(e1.getMessage());
					uiPasswdView.exceptionGuest.setForeground(Color.red);
					uiPasswdView.update();
				}
			}
		}
		else if(e.getSource().equals(uiPasswdView.close)){
			uiPasswdView.kill();
		}
	}
}